using FytSoa.Application.Cm.Param;
using FytSoa.Common.Extensions;
using FytSoa.Domain.Cm;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Cm;

/// <summary>
/// 社区-勋章用户获得服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v6")]
public class CmMedalUserService : IApplicationService 
{
    private readonly SugarRepository<CmMedalUser> _thisRepository;
    public CmMedalUserService(SugarRepository<CmMedalUser> thisRepository)
    {
        _thisRepository = thisRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CmMedalUserDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Status=="1",m=>m.IsNeck)
            .WhereIF(param.Id!=0,m=>m.UserId==param.Id)
            .Includes(m=>m.Medal)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<CmMedalUserDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CmMedalUserDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<CmMedalUserDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(CmMedalUserAdd model)
    {
        var isAny = await _thisRepository.IsAnyAsync(m => m.UserId == model.UserId && m.MedalId == model.MedalId);
        if (isAny)
        {
            throw new BusinessException("已经为当前用户奖励过已选择的勋章~");
        }
        return await _thisRepository.InsertAsync(model.Adapt<CmMedalUser>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(CmMedalUserAdd model) =>
        await _thisRepository.UpdateAsync(model.Adapt<CmMedalUser>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
